package cn.itlight.basic.service.impl;

import cn.itlight.basic.constant.BaseConstants;
import cn.itlight.basic.exception.BusinessException;
import cn.itlight.basic.jwt.JwtUtils;
import cn.itlight.basic.jwt.RsaUtils;
import cn.itlight.basic.jwt.UserInfo;
import cn.itlight.basic.service.ILoginService;
import cn.itlight.basic.utils.AjaxResult;
import cn.itlight.basic.utils.HttpUtil;
import cn.itlight.basic.utils.MD5Utils;
import cn.itlight.basic.utils.StrUtils;
import cn.itlight.basic.vo.LoginVo;
import cn.itlight.basic.vo.WxVo;
import cn.itlight.system.domain.Menu;
import cn.itlight.system.mapper.MenuMapper;
import cn.itlight.system.mapper.PermissionMapper;
import cn.itlight.user.domain.Logininfo;
import cn.itlight.user.domain.User;
import cn.itlight.user.domain.Wxuser;
import cn.itlight.user.mapper.LogininfoMapper;
import cn.itlight.user.mapper.UserMapper;
import cn.itlight.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Value("${jwt.rsa.pri}")
    private String rsaPrivate;

    //    /*
//    * @Title: account
//    * @Description: token方案账号登录
//    * @Author: TomLiu
//    * @Version: 1.0
//    * @Date:  2022/7/14 14:49
//    * @Parameters:
//    * @Return
//    */
//    public HashMap<String, Object> account(LoginVo loginVo) {
//        String username = loginVo.getUsername();
//        String password = loginVo.getPassword();
//        String codeValue = loginVo.getCodeValue();
//        String type = loginVo.getType();
//        // 校验参数不为空
//        if (StringUtils.isEmpty(username) ||
//            StringUtils.isEmpty(type)){
//            throw new BusinessException("参数不能为空！");
//        }
//        if (StringUtils.isEmpty(password) && StringUtils.isEmpty(codeValue)){
//            throw new BusinessException("参数不能为空！");
//        }
//
//
//        // 2.根据账号&type查询用户，字段对应有三个username or phone or email and type
//        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username, type);
//
//        // 3.判断账号是否存在，不存在抛出异常
//        if (logininfo == null){
//            throw new BusinessException("账号密码错误，请重新输入！");
//        }
//
//        if (StringUtils.isEmpty(codeValue)){
//            // 4.判断密码是否一致，需要加盐加密比较
//            String passwordTmp = MD5Utils.encrypByMd5(logininfo.getSalt() + password);
//            System.out.println(logininfo.getSalt());
//            System.out.println(passwordTmp);
//            if(!logininfo.getPassword().equals(passwordTmp)){
//                throw new BusinessException("账号密码错误，请重新输入！");
//            }
//        } else {
//            // 1.为空校验
//            String phoneCodeKey = BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_PREFIX + username;
//            Object phoneCodeValueRedis = redisTemplate.opsForValue().get(phoneCodeKey);
//            // 2.验证手机号是否一致，验证码是否过期
//            if (phoneCodeValueRedis == null){
//                throw new BusinessException("验证码已失效，请重试！");
//            }
//            // 3.判断验证码是否正确
//            String split = phoneCodeValueRedis.toString().split(":")[1];
//            if (!split.equalsIgnoreCase(codeValue)){
//                throw new BusinessException("验证码错误，请重试！");
//            }
//        }
//
//
//        // 5.生成UUID作为key
//        String token = UUID.randomUUID().toString();
//
//        // 6.将uuid&&logininfo设置到redis中，设置30分钟有效期
//        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
//        // 7.把Logininfo对象的敏感信息置为空，作为value
//        logininfo.setSalt("");
//        logininfo.setPassword("");
//        // 8.将uuid&&logininfo存入到map中，返回给前端
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("token", token);
//        map.put("logininfo", logininfo);
//        return map;
//    }
    /*
     * @Title: account
     * @Description: jwt方案账号登录
     * @Author: TomLiu
     * @Version: 1.0
     * @Date:  2022/7/14 14:49
     * @Parameters:
     * @Return
     */
    public HashMap<String, Object> account(LoginVo loginVo) {
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();
        String codeValue = loginVo.getCodeValue();
        String type = loginVo.getType();
        // 校验参数不为空
        if (StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(type)) {
            throw new BusinessException("参数不能为空！");
        }
        if (StringUtils.isEmpty(password) && StringUtils.isEmpty(codeValue)) {
            throw new BusinessException("参数不能为空！");
        }


        // 2.根据账号&type查询用户，字段对应有三个username or phone or email and type
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username, type);

        // 3.判断账号是否存在，不存在抛出异常
        if (logininfo == null) {
            throw new BusinessException("账号密码错误，请重新输入！");
        }

        if (StringUtils.isEmpty(codeValue)) {
            // 4.判断密码是否一致，需要加盐加密比较
            String passwordTmp = MD5Utils.encrypByMd5(logininfo.getSalt() + password);
            System.out.println(logininfo.getSalt());
            System.out.println(passwordTmp);
            if (!logininfo.getPassword().equals(passwordTmp)) {
                throw new BusinessException("账号密码错误，请重新输入！");
            }
        } else {
            // 1.为空校验
            String phoneCodeKey = BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_PREFIX + username;
            Object phoneCodeValueRedis = redisTemplate.opsForValue().get(phoneCodeKey);
            // 2.验证手机号是否一致，验证码是否过期
            if (phoneCodeValueRedis == null) {
                throw new BusinessException("验证码已失效，请重试！");
            }
            // 3.判断验证码是否正确
            String split = phoneCodeValueRedis.toString().split(":")[1];
            if (!split.equalsIgnoreCase(codeValue)) {
                throw new BusinessException("验证码错误，请重试！");
            }
        }

//        UserInfo userInfo = new UserInfo();
//        userInfo.setLogininfo(logininfo);
//        // 8.将uuid&&logininfo存入到map中，返回给前端
//        HashMap<String, Object> map = new HashMap<>();
//        if ("0".equals(type)){
//            List<String> permissions = permissionMapper.loadOwnPermissionByLogininId(logininfo.getId());
//            List<Menu> menus = menuMapper.loadOwnMenuByLogininId(logininfo.getId());
//            userInfo.setPermissions(permissions);
//            userInfo.setMenus(menus);
//            map.put("permissions", permissions);
//            map.put("menus", menus);
//        }
//        // 1 获取token
//        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource(rsaPrivate).getFile());
//        String token =JwtUtils.generateTokenExpireInMinutes(userInfo, privateKey, 30);
//        // 7.把Logininfo对象的敏感信息置为空，作为value
//        logininfo.setSalt("");
//        logininfo.setPassword("");
//
//        map.put("token", token);
//        map.put("logininfo", logininfo);
        return sb(logininfo);
    }

    public HashMap<String, Object> sb(Logininfo logininfo){
        UserInfo userInfo = new UserInfo();
        userInfo.setLogininfo(logininfo);
        // 8.将uuid&&logininfo存入到map中，返回给前端
        HashMap<String, Object> map = new HashMap<>();
        if (logininfo.getType() == 0){
            List<String> permissions = permissionMapper.loadOwnPermissionByLogininId(logininfo.getId());
            List<Menu> menus = menuMapper.loadOwnMenuByLogininId(logininfo.getId());
            userInfo.setPermissions(permissions);
            userInfo.setMenus(menus);
            map.put("permissions", permissions);
            map.put("menus", menus);
        }
        // 1 获取token
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource(rsaPrivate).getFile());
        String token =JwtUtils.generateTokenExpireInMinutes(userInfo, privateKey, 3000);
        // 7.把Logininfo对象的敏感信息置为空，作为value
        logininfo.setSalt("");
        logininfo.setPassword("");

        map.put("token", token);
        map.put("logininfo", logininfo);
        return map;
    }


    /*
     * @Title: wechat
     * @Description: 微信登录判断是否第一次
     * @Author: TomLiu
     * @Version: 1.0
     * @Date:  2022/7/10 16:46
     * @Parameters:
     * @Return
     */
    @Override
    public AjaxResult wechat(WxVo wxVo) {
        // 非空校验
        String code = wxVo.getCode();
        if (StringUtils.isEmpty(code)) {
            throw new BusinessException("参数不能为空！");
        }
        // 根据code获得access_token
        String tokenurl = BaseConstants.WxConstant.TOKEN_URL
                .replace("APPID", BaseConstants.WxConstant.APPID)
                .replace("SECRET", BaseConstants.WxConstant.SECRET)
                .replace("CODE", code);
        String httpGet = HttpUtil.httpGet(tokenurl);

        JSONObject jsonObject = JSONObject.parseObject(httpGet);
        // 根据openId查询wxUser表，看微信用户是否存在并且绑定账号
        Wxuser wxuser = wxuserMapper.loadByOpenId(jsonObject.getString("openid"));
        // 存在并且绑定，让用户直接免密登录
        if (wxuser != null && wxuser.getUserId() != null) {
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
//            // 5.生成UUID作为key
//            String token = UUID.randomUUID().toString();
//            // 6.将uuid&&logininfo设置到redis中，设置30分钟有效期
//            redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
//            // 7.把Logininfo对象的敏感信息置为空，作为value
//            logininfo.setSalt("");
//            logininfo.setPassword("");
//            // 8.将uuid&&logininfo存入到map中，返回给前端
//            Map<String, Object> map = new HashMap<>();
//            map.put("token", token);
//            map.put("logininfo", logininfo);
            HashMap<String, Object> map = sb(logininfo);
            return AjaxResult.me().setResultObj(map);
        }
        // 不存在，传递access_token&openId到页面，并且success=false&message=nobinder
        String paramStr = "?accessToken=" + jsonObject.getString("access_token") + "&openId=" + jsonObject.getString("openid");
        return AjaxResult.me().setSuccess(false).setMessage("nobinder").setResultObj(paramStr);
    }

    @Override
    public Map<String, Object> binder(WxVo wxVo) {

        String accessToken = wxVo.getAccessToken();
        String phone = wxVo.getPhone();
        String verifyCode = wxVo.getVerifyCode();
        String openId = wxVo.getOpenId();

        // 非空校验
        if (StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(verifyCode)
                || StringUtils.isEmpty(accessToken)
                || StringUtils.isEmpty(openId)) {
        }

        // 手机验证码校验
        // 为空校验
        String phoneCodeKey = BaseConstants.VerifyCodeConstant.BUSINESS_BINDER_PREFIX + phone;
        Object phoneCodeValueRedis = redisTemplate.opsForValue().get(phoneCodeKey);
        // 判断验证码是否正确
        String phoneCode = phoneCodeValueRedis.toString().split(":")[1];
        if (!phoneCode.equalsIgnoreCase(verifyCode)) {
            throw new BusinessException("手机验证码错误，请重新输入！");
        }

        // 根据手机号查询用户是否存在，t_user
        User user = userMapper.loadByPhone(phone);
        Logininfo logininfo = null;
        if (user == null) {
            // 1.初始化user对象
            user = smsCodeDto2User(phone);
            //  2.拷贝user对象到logininfo中
            logininfo = user2Logininfo(user);
            //  3.保存logininfo
            logininfoMapper.save(logininfo);
            // 4.设置logininfo主键到user对象中
            user.setLogininfoId(logininfo.getId());
            // 5.保存user对象
            userMapper.save(user);
        } else {// 根据userId得到logininfo对象
            logininfo = logininfoMapper.loadByUserId(user.getId());
        }

        // 把根据access_token&openId得到微信用户基本信息的URL设置为常量，修改URL中的参数
        String wxUserUrl = BaseConstants.WxConstant.WXUSER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String wxUserStr = HttpUtil.httpGet(wxUserUrl);

        // 使用JSON.parseObject(JSON字符串,Wxuser.class)，得到Wxuser对象
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
        // 将userId设置到wxUser对象的user_id字段中
        wxuser.setUserId(user.getId());
        // 保存wxUser
        wxuserMapper.save(wxuser);
        // 6.返回成功登录map
//        // 5.生成UUID作为key
//        String token = UUID.randomUUID().toString();
//        // 6.将uuid&&logininfo设置到redis中，设置30分钟有效期
//        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
//        // 7.把Logininfo对象的敏感信息置为空，作为value
//        logininfo.setSalt("");
//        logininfo.setPassword("");
//        // 8.将uuid&&logininfo存入到map中，返回给前端
//        Map<String, Object> map = new HashMap<>();
//        map.put("token", token);
//        map.put("logininfo", logininfo);
        return sb(logininfo);

    }

    private User smsCodeDto2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String saltPassword = MD5Utils.encrypByMd5(salt + "1");
        user.setPassword(saltPassword);
        user.setSalt(salt);
        // 此处最好给用户发个短信，告知他初始密码是多少
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }
}
